package DBLayer;

import ModelLayer.*;
import java.sql.*;
import java.util.ArrayList;

public class DBGrownup implements DBGrownupIF
{
	private Connection con;
    
    public DBGrownup() 
    {
      con = DBConnection.getInstance().getDBcon();
    }
    
    public ArrayList<Grownup> getAllGrownups(boolean retriveAssociation)
    {
        return miscWhere("", retriveAssociation);
    }

    public Grownup searchGrownupID(int GrownupID, boolean retriveAssociation)
    {   
    	String wClause = "GrownupID = " + GrownupID + "";
        return singleWhere(wClause, retriveAssociation);
    }
	
	private ArrayList<Grownup> miscWhere(String wClause, boolean retrieveAssociation)
	{
		ResultSet results;
		ArrayList<Grownup> GrownupList = new ArrayList<Grownup>();	
		
		String query =  buildQuery(wClause);
  
  		try
  		{
	 		Statement stmt = con.createStatement();
	 		stmt.setQueryTimeout(5);
	 		results = stmt.executeQuery(query);
	 		
			while( results.next() )
			{
				Grownup gObj = new Grownup();
				gObj = buildGrownup(results);
				GrownupList.add(gObj);
			}
			stmt.close();
		}
	 	catch(Exception e)
	 	{
	 		System.out.println("Query exception - select: "+e);
			e.printStackTrace();
	 	}
		return GrownupList;
	}
	
	private Grownup singleWhere(String wClause, boolean retrieveAssociation)
	{
		ResultSet results;
		Grownup gObj = new Grownup();
	    String query =  buildQuery(wClause);
//        System.out.println(query);
		try
		{
	 		Statement stmt = con.createStatement();
	 		stmt.setQueryTimeout(5);
	 		results = stmt.executeQuery(query);
	 		
	 		if( results.next() )
	 		{
	 			gObj = buildGrownup(results);
	 			stmt.close();
			}
		}	
	 	catch(Exception e)
	 	{
	 		System.out.println("Query exception: "+e);
	 	}
		return gObj;
	}

	private String buildQuery(String wClause)
	{
	    String query="SELECT * FROM Grownup";
		
		if (wClause.length()>0)
			query=query+" WHERE "+ wClause;		
		return query;
	}

	private Grownup buildGrownup(ResultSet results)
      {   
		Grownup gObj = new Grownup();
          try
          { /* GrownupID */
                gObj.setGrownupID(results.getInt("GrownupID"));
          }
         catch(Exception e)
         {
             System.out.println("error in building the Parent object");
         }
         return gObj;
      }

}
